import copy
import json
from abc import ABC, abstractmethod

from forward.api.admin.schemas.setting import SettingSmsSaveInSchema
from forward.config import get_settings
from forward.utils.config import ConfigUtil


class SettingSmsService:
    """短信配置服务实现类"""

    engines = {
        "aliyun": {"name": "阿里云短信", "alias": "aliyun"},
        "tencent": {"name": "腾讯云短信", "alias": "tencent"},
    }

    async def list(self) -> list:
        """短信引擎列表"""
        engine = await ConfigUtil.get_val("sms", "default", "aliyun")
        res = []
        for k, v in copy.deepcopy(self.engines).items():
            status = 0
            if k == engine:
                status = 1
            v["status"] = str(status)
            res.append(v)
        return res

    async def detail(self, alias: str) -> dict:
        """短信引擎详情"""
        is_prod = get_settings().mode == "prod"

        engine = await ConfigUtil.get_val("sms", "default", "local")
        config = await ConfigUtil.get_map("sms", alias)
        if not config:
            config = {}
        res = {
            "name": config.get("name", ""),
            "status": 1 if engine == alias else 0,
            "alias": alias,
            "sign": config.get("sign", ""),
        }
        if alias == "aliyun":
            res["appKey"] = "******" if is_prod else config.get("appKey", "")
            res["secretKey"] = "******" if is_prod else config.get("secretKey", "")
        elif alias == "tencent":
            res["appId"] = "******" if is_prod else config.get("appId", "")
            res["secretId"] = "******" if is_prod else config.get("secretId", "")
            res["secretKey"] = "******" if is_prod else config.get("secretKey", "")
        elif alias == "huawei":
            pass
        return res

    async def save(self, save_in: SettingSmsSaveInSchema):
        """短信引擎保存"""
        await ConfigUtil.set(
            "sms",
            save_in.alias,
            json.dumps(save_in.dict(exclude_none=True), ensure_ascii=False),
        )
        engine = await ConfigUtil.get_val("sms", "default", "")
        if save_in.status == 1:
            await ConfigUtil.set("sms", "default", save_in.alias)
        elif engine == save_in.alias and save_in.status == 0:
            await ConfigUtil.set("sms", "default", "")

    @classmethod
    async def instance(cls):
        """实例化"""
        return cls()
